package com.android.dopewars;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

public class DrugBuySell extends Activity {
	
	public static final int NUM_LOCATIONS = 6;
	
	public static final int LOCATION_CHANGE_1 = Menu.FIRST;
	public static final int LOCATION_CHANGE_2 = Menu.FIRST + 1;
	public static final int LOCATION_CHANGE_3 = Menu.FIRST + 2;
	public static final int LOCATION_CHANGE_4 = Menu.FIRST + 3;
	public static final int LOCATION_CHANGE_5 = Menu.FIRST + 4;
	public static final int LOCATION_CHANGE_6 = Menu.FIRST + 5;
	public static final int END_GAME = Menu.FIRST + 6;
	
	public static final int LOAN_SHARK = 0;
	public static final int BANK = 1;
	public static final int MUGGED = 4;
	public static final int FIGHT = 5;
	public static final int SELL_DRUG = 6;
	public static final int BUY_DRUG = 7;
	public static final int STORE = 8;
	
	public class BuyListener implements View.OnClickListener {
		public BuyListener(int drug_index) {
			drug_index_ = drug_index;
		}
		
		public void onClick(View v) {
			Global.buy_sell_drug_ = drug_index_;
			Intent i = new Intent(v.getContext(), DrugBuy.class);
			startActivityForResult(i, BUY_DRUG);
		}
		
		private int drug_index_;
		
	}
	
	public class SellListener implements View.OnClickListener {
		public SellListener(int drug_index) {
			drug_index_ = drug_index;
		}
		
		public void onClick(View v) {
			Global.buy_sell_drug_ = drug_index_;
			Intent i = new Intent(v.getContext(), DrugSell.class);
			startActivityForResult(i, SELL_DRUG);
		}
		
		private int drug_index_;
	}

	/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.drug_buy_sell);
        
        //Setup the buy and sell button listeners
        ((Button)findViewById(R.id.go_to_loan_shark)).setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
    			Intent i = new Intent(v.getContext(), LoanShark.class);
    			startActivityForResult(i, LOAN_SHARK);
    		}
        });
        ((Button)findViewById(R.id.go_to_bank)).setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
    			Intent i = new Intent(v.getContext(), Bank.class);
    			startActivityForResult(i, BANK);
    		}
        });
        ((Button)findViewById(R.id.go_to_store)).setOnClickListener(new View.OnClickListener() {
        	public void onClick(View v) {
    			Intent i = new Intent(v.getContext(), Store.class);
    			startActivityForResult(i, STORE);
    		}
        });
        
        Global.days_since_location_.setSize(NUM_LOCATIONS);
        for (int i = 0; i < NUM_LOCATIONS; ++i) {
        	Global.days_since_location_.setElementAt(0, i);
        }
        
        moveLocation();
    }
    
    
    
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        boolean result = super.onCreateOptionsMenu(menu);
        menu.add(1, LOCATION_CHANGE_1, 0, "The Bronx");
        menu.add(2, LOCATION_CHANGE_2, 1, "Westchester");
        menu.add(3, LOCATION_CHANGE_3, 2, "Central Park");
        menu.add(4, LOCATION_CHANGE_4, 3, "Manhattan");
        menu.add(5, LOCATION_CHANGE_5, 4, "Coney Island");
        menu.add(6, LOCATION_CHANGE_6, 5, "Brooklyn");
        menu.add(7, END_GAME, 6, "End game");
        return result;
    }
    
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
    	menu.setGroupVisible(1, (Global.location_ != 0) && (Global.days_left_ > 0));
    	menu.setGroupVisible(2, (Global.location_ != 1) && (Global.days_left_ > 0));
    	menu.setGroupVisible(3, (Global.location_ != 2) && (Global.days_left_ > 0));
    	menu.setGroupVisible(4, (Global.location_ != 3) && (Global.days_left_ > 0));
    	menu.setGroupVisible(5, (Global.location_ != 4) && (Global.days_left_ > 0));
    	menu.setGroupVisible(6, (Global.location_ != 5) && (Global.days_left_ > 0));
    	menu.setGroupVisible(7, Global.days_left_ <= 0);
    	return true;
    }
    
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case LOCATION_CHANGE_1:
        	Global.location_ = 0;
        	moveLocation();
            return true;
        case LOCATION_CHANGE_2:
        	Global.location_ = 1;
        	moveLocation();
        	return true;
        case LOCATION_CHANGE_3:
        	Global.location_ = 2;
        	moveLocation();
        	return true;
        case LOCATION_CHANGE_4:
        	Global.location_ = 3;
        	moveLocation();
        	return true;
        case LOCATION_CHANGE_5:
        	Global.location_ = 4;
        	moveLocation();
        	return true;
        case LOCATION_CHANGE_6:
        	Global.location_ = 5;
        	moveLocation();
        	return true;
        case END_GAME:
    		Intent i = new Intent();
    		setResult(RESULT_OK, i);
    		finish();
        }
        return super.onOptionsItemSelected(item);
    }
    
    /** Called when the activity returns. */
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    	super.onActivityResult(requestCode, resultCode, intent);
    	if ((requestCode == FIGHT) && (resultCode != RESULT_OK)) {
			Global.ui_messages_.clear();
			Global.ui_messages_.add(Global.officer_name_ + " loves your cookies. So much so that he had you removed from the picture.. permanently");
			Global.current_drugs_.clear();
			Global.days_left_ = 0;
		}
    	updateUI();
    }
    
    public void moveLocation() {
    	Global.ui_messages_.clear();

    	// Other events could modify these so set this up first
    	setupDrugPrices();
    	
    	// check for a random event
    	if (!Global.first_day_) {
	    	int random_event = Global.randomEvent();
	    	Global.unstockStore();
	    	if (random_event == Global.RANDOM_EVENT_STORE) {
	    		Global.stockStore();
	    		double store_message_chooser = Global.rand_gen_.nextDouble();
	    		if (store_message_chooser < 0.25) {
	    			Global.ui_messages_.add("Hey! The store is open today!");
	    		} else if (store_message_chooser < 0.5) {
	    			Global.ui_messages_.add("A bakery supply store is selling weapons and out of the back room!");
	    		} else if (store_message_chooser < 0.75) {
	    			Global.ui_messages_.add("The mayor loves your bakery and wants to make sure you are protected!");
	    		} else {
	    			Global.ui_messages_.add("The President loves your bakery and personally vows protection");
	    		}
	    	} else if (random_event == Global.RANDOM_EVENT_MUGGED) {
	    		Intent i = new Intent(this, Mugged.class);
	    		startActivityForResult(i, MUGGED);
	    	} else if (random_event == Global.RANDOM_EVENT_FIGHT) {
	    		Intent i = new Intent(this, Fight.class);
	    		startActivityForResult(i, FIGHT);
	    	}
    	}
    	
    	Global.first_day_ = false;
    	for (int i = 0; i < NUM_LOCATIONS; ++i) {
    		Global.days_since_location_.setElementAt(Global.days_since_location_.elementAt(i) + 1, i);
    	}
    	Global.days_since_location_.setElementAt(0, Global.location_);
    	Global.days_left_ -= 1;
    	Global.dealer_.setDebt(Global.dealer_.debt() + (int)(Global.dealer_.debt() * 0.05));
    	Global.dealer_.setBank(Global.dealer_.bank() + (int)(Global.dealer_.bank() * 0.05));
    	randomMessages();
    	updateUI();
    }
    
    public void randomMessages() {
    	double song_random = Global.rand_gen_.nextDouble();
    	if (song_random < 0.10) {
    		int song_choice = Global.rand_gen_.nextInt(Global.songs_.size());
    		int location_random = Global.rand_gen_.nextInt(3);
    		switch (location_random) {
    		case 0:
    			Global.ui_messages_.add("You hear someone humming " + Global.songs_.elementAt(song_choice) + " on the subway.");
    			break;
    		case 1:
    			Global.ui_messages_.add("A cab rolls by blaring " + Global.songs_.elementAt(song_choice) + ".");
    			break;
    		case 2:
    			Global.ui_messages_.add("Some guys on the corner are grooving to " + Global.songs_.elementAt(song_choice) + " on their boombox.");
    			break;
    		}
    	}
    	double message_random = Global.rand_gen_.nextDouble();
    	if (message_random < 0.10) {
    		int message_choice = Global.rand_gen_.nextInt(Global.random_messages_.size());
    		int source_random = Global.rand_gen_.nextInt(3);
    		switch (source_random) {
    		case 0:
    			Global.ui_messages_.add("A passing woman on the subway says \"" +
    					Global.random_messages_.elementAt(message_choice) + "\"");
    			break;
    		case 1:
    			Global.ui_messages_.add("Some random dude with a huge afro says \"" +
    					Global.random_messages_.elementAt(message_choice) + "\"");
    			break;
    		case 2:
    			Global.ui_messages_.add("A cab driver says, as he drives by, \"" +
    					Global.random_messages_.elementAt(message_choice) + "\"");
    			break;
    		}
    	}
    }
    
    public void updateUI() {
    	
    	// Container for messages
    	LinearLayout message_container = (LinearLayout)findViewById(R.id.message_container);
    	for (int i = message_container.getChildCount(); i < Global.ui_messages_.size(); ++i) {
    		TextView next_view = new TextView(this);
    		next_view.setLayoutParams(new LinearLayout.LayoutParams(
		        		LinearLayout.LayoutParams.FILL_PARENT,
		        		LinearLayout.LayoutParams.WRAP_CONTENT));
    		next_view.setTextSize((float)12.0);
    		next_view.setBackgroundColor(Color.rgb(74 - 10 * i, 74 - 10 * i, 74 - 10 * i));
    		next_view.setTextColor(Color.rgb(
    				(i % 3 == 0) ? 255 : 180, ((i + 1) % 3 == 0) ? 255 : 180, ((i + 2) % 3 == 0) ? 255 : 180));
    		next_view.setText(Global.ui_messages_.elementAt(i));
    		message_container.addView(next_view);
    	}
    	for (int i = 0; i < Global.ui_messages_.size(); ++i) {
    		message_container.getChildAt(i).setVisibility(View.VISIBLE);
    		((TextView)message_container.getChildAt(i)).setText(Global.ui_messages_.elementAt(i));
    	}
    	for (int i = Global.ui_messages_.size(); i < message_container.getChildCount(); ++i) {
    		message_container.getChildAt(i).setVisibility(View.GONE);
    	}

    	TableLayout drug_container = (TableLayout)findViewById(R.id.drug_container);
    	for (int i = drug_container.getChildCount(); i < Global.current_drugs_.size(); ++i) {
    		TableRow next_row = new TableRow(this);
    		Button sell_button = new Button(this, null, android.R.attr.buttonStyleSmall);
    		sell_button.setLayoutParams(new TableRow.LayoutParams(
    				TableRow.LayoutParams.WRAP_CONTENT,
    				TableRow.LayoutParams.WRAP_CONTENT, (float)1.0));
    		sell_button.setText("sell");
    		sell_button.setOnClickListener(new SellListener(i));
    		next_row.addView(sell_button);
    		TextView name = new TextView(this);
    		TableRow.LayoutParams params = new TableRow.LayoutParams(
    				TableRow.LayoutParams.WRAP_CONTENT,
    				TableRow.LayoutParams.WRAP_CONTENT, (float)1.0);
    		params.rightMargin = 5;
    		name.setLayoutParams(params);
    		name.setTextSize((float)16.0);
    		name.setTextColor(Color.WHITE);
    		name.setGravity(Gravity.RIGHT);
    		next_row.addView(name);
    		TextView price = new TextView(this);
    		params = new TableRow.LayoutParams(
    				TableRow.LayoutParams.WRAP_CONTENT,
    				TableRow.LayoutParams.WRAP_CONTENT, (float)1.0);
    		params.leftMargin = 5;
    		price.setLayoutParams(params);
    		price.setTextSize((float)16.0);
    		price.setGravity(Gravity.LEFT);
    		price.setTextColor(Color.rgb(86,210,86));
    		price.setTypeface(Typeface.DEFAULT_BOLD);
    		next_row.addView(price);
    		Button buy_button = new Button(this, null, android.R.attr.buttonStyleSmall);
    		buy_button.setLayoutParams(new TableRow.LayoutParams(
    				TableRow.LayoutParams.WRAP_CONTENT,
    				TableRow.LayoutParams.WRAP_CONTENT, (float)1.0));
    		buy_button.setText("buy");
    		buy_button.setOnClickListener(new BuyListener(i));
    		next_row.addView(buy_button);
    		drug_container.addView(next_row);
    	}
    	for (int i = 0; i < Global.current_drugs_.size(); ++i) {
    		TableRow next_row = ((TableRow)drug_container.getChildAt(i));
    		next_row.setVisibility(View.VISIBLE);
    		boolean has_drug = Global.dealer_.drugQuantity(Global.current_drugs_.elementAt(i).name()) > 0;
    		if (has_drug) {
    			next_row.setBackgroundDrawable(this.getResources().getDrawable(R.drawable.magic_clear_background));
    			((Button)next_row.getChildAt(0)).setEnabled(true);
    		} else {
    			next_row.setBackgroundDrawable(null);
    			((Button)next_row.getChildAt(0)).setEnabled(false);
    		}
    		TextView name_view = (TextView)next_row.getChildAt(1);
    		String name_text = Global.current_drugs_.elementAt(i).name();
    		if (has_drug) {
    			name_text += " (" + Integer.toString(Global.dealer_.drugQuantity(Global.current_drugs_.elementAt(i).name())) + ")";
    			name_view.setTextColor(Color.rgb(0,0,0));
    		} else {
    			name_view.setTextColor(Color.rgb(255,255,255));
    		}
    		name_view.setText(name_text);
    		TextView price_view = (TextView)next_row.getChildAt(2);
    		if (has_drug) {
    			price_view.setTextColor(Color.rgb(26,170,26));
    		} else {
    			price_view.setTextColor(Color.rgb(86,210,86));
    		}
    		price_view.setText("$" + Integer.toString(Global.current_drugs_.elementAt(i).currentPrice()));
    		if (Global.dealer_.cash() > Global.current_drugs_.elementAt(i).currentPrice() &&
    			Global.dealer_.spaceAvailable() > 0) {
    			((Button)next_row.getChildAt(3)).setEnabled(true);
    		} else {
    			((Button)next_row.getChildAt(3)).setEnabled(false);
    		}
    	}
    	for (int i = Global.current_drugs_.size(); i < drug_container.getChildCount(); ++i) {
    		drug_container.getChildAt(i).setVisibility(View.GONE);
    	}

    	if (Global.location_ == 0) { ((TextView)findViewById(R.id.location_name)).setText("The Bronx");
    	} else if (Global.location_ == 1) { ((TextView)findViewById(R.id.location_name)).setText("Westchester");
    	} else if (Global.location_ == 2) { ((TextView)findViewById(R.id.location_name)).setText("Central Park");
    	} else if (Global.location_ == 3) { ((TextView)findViewById(R.id.location_name)).setText("Manhattan");
    	} else if (Global.location_ == 4) { ((TextView)findViewById(R.id.location_name)).setText("Coney Island");
    	} else if (Global.location_ == 5) { ((TextView)findViewById(R.id.location_name)).setText("Brooklyn");
    	} else { ((TextView)findViewById(R.id.location_name)).setText("The Matrix"); }
    	
    	if (Global.location_ == 0) {
    		findViewById(R.id.go_to_loan_shark).setVisibility(View.VISIBLE);
    		findViewById(R.id.go_to_bank).setVisibility(View.VISIBLE);
    	} else {
    		findViewById(R.id.go_to_loan_shark).setVisibility(View.GONE);
    		findViewById(R.id.go_to_bank).setVisibility(View.GONE);
    	}
    	
    	if (Global.showStore()) {
    		findViewById(R.id.go_to_store).setVisibility(View.VISIBLE);
    	} else {
    		findViewById(R.id.go_to_store).setVisibility(View.GONE);
    	}
    	
    	((TextView)findViewById(R.id.dealer_name)).setText(Global.dealer_.name());
    	((TextView)findViewById(R.id.days_left)).setText(Integer.toString(Global.days_left_) + " days left");
    	((TextView)findViewById(R.id.dealer_cash)).setText("c: $" + Integer.toString(Global.dealer_.cash()));
    	if (Global.dealer_.debt() > 0) {
    		findViewById(R.id.dealer_debt).setVisibility(View.VISIBLE);
        	((TextView)findViewById(R.id.dealer_debt)).setText("d: $" + Integer.toString(Global.dealer_.debt()));
    	} else {
    		findViewById(R.id.dealer_debt).setVisibility(View.GONE);
    	}
    	if (Global.dealer_.bank() > 0) {
    		findViewById(R.id.dealer_bank).setVisibility(View.VISIBLE);
        	((TextView)findViewById(R.id.dealer_bank)).setText("b: $" + Integer.toString(Global.dealer_.bank()));
    	} else {
    		findViewById(R.id.dealer_bank).setVisibility(View.GONE);
    	}
        ((TextView)findViewById(R.id.dealer_space)).setText("s: " + Integer.toString(Global.dealer_.spaceAvailable()));
    	if (Global.dealer_.numGuns() > 0) {
    		findViewById(R.id.dealer_guns).setVisibility(View.VISIBLE);
        	((TextView)findViewById(R.id.dealer_guns)).setText("g: " + Integer.toString(Global.dealer_.numGuns()));
    	} else {
    		findViewById(R.id.dealer_guns).setVisibility(View.GONE);
    	}
    	((TextView)findViewById(R.id.dealer_health)).setText("h: " + Integer.toString(Global.dealer_.health()));
    }

    public void setupDrugPrices() {
    	int num_drugs_to_add = 6 + Global.rand_gen_.nextInt(3);
    	int days_since_location = Global.days_since_location_.elementAt(Global.location_);
    	if (days_since_location < 3) {
    		num_drugs_to_add -= 1;
    	}
    	if (days_since_location > 5) {
    		num_drugs_to_add += 1;
    	}
    	if (days_since_location > 8) {
    		num_drugs_to_add += 1;
    	}
    	if (days_since_location > 11) {
    		num_drugs_to_add += 1;
    	}
    	boolean[] drug_added = new boolean[Global.available_drugs_.size()];
    	for (int i = 0; i < Global.available_drugs_.size(); ++i) {
    		drug_added[i] = false;
    	}
    	int num_drugs_left = Global.available_drugs_.size();
    	while (num_drugs_left > Global.available_drugs_.size() - num_drugs_to_add) {
    		int next_drug_to_add = Global.rand_gen_.nextInt(num_drugs_left);
    		int drug_number = 0;
    		while (drug_added[drug_number]) {
    			++drug_number;
    		}
    		int drugs_skipped = 0;
    		while (drugs_skipped < next_drug_to_add) {
    			if (drug_added[drug_number] == false) {
    				++drugs_skipped;
    			}
    			++drug_number;
    		}
    		while (drug_added[drug_number]) {
    			++drug_number;
    		}
    		drug_added[drug_number] = true;
    		--num_drugs_left;
    	}
    	Global.current_drugs_.clear();
    	for (int i = 0; i < Global.available_drugs_.size(); ++i) {
    		if (drug_added[i]) {
    			Global.available_drugs_.elementAt(i).setNewPrice(days_since_location);
    			Global.current_drugs_.add(Global.available_drugs_.elementAt(i));
    		}
    	}
    }
}